package org.melanesia.beans;

import java.lang.reflect.Method;

import org.melanesia.beans.exceptions.PropertyAccessException;

/**
 * Property getter using method access.
 * 
 * @author marcin.kielar
 */
public class MethodGetter implements Getter {

    /** Reflection method for accessing the property. */
    private final Method method;

    /**
     * Constructs new <code>MethodGetter</code> with method accessing the
     * property.
     * 
     * @param method
     *            method accessing the property
     */
    MethodGetter(final Method method) {
        this.method = method;
    }

    @Override
    public final Object get(final Object bean) {
        boolean accessible = method.isAccessible();

        try {
            if (!accessible) {
                BeanUtils.setAccessible(method, true);
            }
            return method.invoke(bean);

        } catch (Throwable t) {
            throw new PropertyAccessException("Cannot get value using method " + method.getName(), t);
        } finally {
            BeanUtils.setAccessible(method, accessible);
        }
    }

    @Override
    public final Class<?> getReturnType() {
        return method.getReturnType();
    }

}
